/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.samhooxee.android.leet;

import java.util.HashMap;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.admob.android.ads.AdManager; 
import com.admob.android.ads.AdView;
import com.samhooxee.android.leet.R;

/**
 * This class provides a basic demonstration of how to write an Android
 * activity. Inside of its window, it places a single view: an EditText that
 * displays and edits some internal text.
 */
public class SkeletonActivity extends Activity {

	private static final int NOTIFY_ME_ID = 1337;

	static final private int BACK_ID = Menu.FIRST;
	static final private int CLEAR_ID = Menu.FIRST + 1;
	static final private int COPY_ID = Menu.FIRST + 2;

	public static final String PREFERENCES_FILE = "TwitterLeetPrefs";
	public static final String EDITSTR_KEY = "editstr";
	public static final String PREVSTR_KEY = "prevstr";
//	String string_edit;
//	String string_prev;

	private EditText mEditor;
	private TextView pEditor;
	private TextView mEditor_len;
	private TextView pEditor_len;
	private HashMap<Character, String> leetmap;

	public SkeletonActivity() {
	}

	/** Called with the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Inflate our UI from its XML layout description.
		setContentView(R.layout.skeleton_activity);
		AdView adView = (AdView)findViewById(R.id.ad); 
		adView.requestFreshAd(); 

		// Find the text editor view inside the layout, because we
		// want to do various programmatic things with it.
		pEditor = (TextView) findViewById(R.id.preview);
		mEditor = (EditText) findViewById(R.id.editor);
		pEditor_len = (TextView) findViewById(R.id.preview_len);
		mEditor_len = (TextView) findViewById(R.id.editor_len);

		// Hook up button presses to the appropriate event handler.
		((Button) findViewById(R.id.copy)).setOnClickListener(mCopyListener);
//		((Button) findViewById(R.id.back)).setOnClickListener(mBackListener);
		((Button) findViewById(R.id.clear)).setOnClickListener(mClearListener);

		mEditor.setText(getText(R.string.main_label));
//		mEditor.setText(getText(R.string.description));
		pEditor.setText(getText(R.string.preview_label));

		// mEditor.setOnKeyListener(mEditListener);
		mEditor.addTextChangedListener(mEditWatch);

		leetmap = initLeetMap();
		notifyMe();
		System.out.println("started !!!");
	}

	private HashMap<Character, String> initLeetMap()
	{
		HashMap<Character, String> lm = new HashMap<Character, String>();
		lm.put('a', "4");
		lm.put('b', "8");
		lm.put('c', "(");
		lm.put('d', "|)");
		lm.put('e', "3");
		lm.put('f', "|=");
		lm.put('g', "6");
		lm.put('h', "|-|");
		lm.put('i', "1");
		lm.put('j', "_|");
		lm.put('k', "|<");
		lm.put('l', "|_");
		lm.put('m', "|v|");
		lm.put('n', "|\\|");
		lm.put('o', "0");
		lm.put('p', "|>");
		lm.put('q', "<|");
		lm.put('r', "|2");
		lm.put('s', "5");
		lm.put('t', "7");
		lm.put('u', "|_|");
		lm.put('v', "\\/");
		lm.put('w', "vv");
		lm.put('x', "><");
		lm.put('y', "-/");
		lm.put('z', "2");
		lm.put('A', "4");
		lm.put('B', "8");
		lm.put('C', "(");
		lm.put('D', "|)");
		lm.put('E', "3");
		lm.put('F', "|=");
		lm.put('G', "6");
		lm.put('H', "|-|");
		lm.put('I', "1");
		lm.put('J', "_|");
		lm.put('K', "|<");
		lm.put('L', "|_");
		lm.put('M', "|v|");
		lm.put('N', "|\\|");
		lm.put('O', "0");
		lm.put('P', "|>");
		lm.put('Q', "<|");
		lm.put('R', "|2");
		lm.put('S', "5");
		lm.put('T', "7");
		lm.put('U', "|_|");
		lm.put('V', "\\/");
		lm.put('W', "vv");
		lm.put('X', "><");
		lm.put('Y', "-/");
		lm.put('Z', "2");
		return lm;
	}
	
	private void notifyMe() {
		final NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification note = new Notification(R.drawable.red_ball,
				getText(R.string.status_msg), System.currentTimeMillis());
		PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(this,
				SkeletonActivity.class), 0);
		note.setLatestEventInfo(this, getText(R.string.Notification_title),
				getText(R.string.Notification_msg), i);
		note.flags |= Notification.FLAG_NO_CLEAR;
		// note.number=++count;
		mgr.notify(NOTIFY_ME_ID, note);
	}

	private void copyToClipboard(CharSequence str) {
		final ClipboardManager mgr = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		mgr.setText(str);
	}
	
	/**
	 * Called when the activity is about to start interacting with the user.
	 */
	@Override
	protected void onResume() {
		super.onResume();
		readInstanceState(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		writeInstanceState(this);
	}

	public boolean readInstanceState(Context c) {
		SharedPreferences p = c.getSharedPreferences(PREFERENCES_FILE,
				MODE_WORLD_READABLE);
		mEditor.setText(p.getString(EDITSTR_KEY, getText(R.string.main_label).toString()));
//		mEditor.setText(p.getString(EDITSTR_KEY, getText(R.string.description).toString()));
		pEditor.setText(p.getString(PREVSTR_KEY, getText(R.string.preview_label).toString()));
		return (p.contains(EDITSTR_KEY));
	}

	public boolean writeInstanceState(Context c) {
		SharedPreferences p = c.getSharedPreferences(
				SkeletonActivity.PREFERENCES_FILE, MODE_WORLD_READABLE);
		SharedPreferences.Editor e = p.edit();
		e.putString(EDITSTR_KEY, mEditor.getText().toString());
		e.putString(PREVSTR_KEY, pEditor.getText().toString());
		return (e.commit());
	}

	/**
	 * Called when your activity's options menu needs to be created.
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		// We are going to create two menus. Note that we assign them
		// unique integer IDs, labels from our string resources, and
		// given them shortcuts.
		menu.add(0, COPY_ID, 0, R.string.copy).setShortcut('0', 'b');
		menu.add(0, CLEAR_ID, 0, R.string.clear).setShortcut('1', 'c');

		return true;
	}

	/**
	 * Called right before your activity's option menu is displayed.
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);

		// Before showing the menu, we need to decide whether the clear
		// item is enabled depending on whether there is text to clear.
		menu.findItem(CLEAR_ID).setVisible(mEditor.getText().length() > 0);

		return true;
	}

	/**
	 * Called when a menu item is selected.
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case COPY_ID:
			copyToClipboard(pEditor.getText());
			finish();
			return true;
		case BACK_ID:
			finish();
			return true;
		case CLEAR_ID:
			mEditor.setText("");
			pEditor.setText("");
			mEditor_len.setText(getText(R.string.input_length).toString()+mEditor.getText().length());
			pEditor_len.setText(getText(R.string.result_length).toString()+pEditor.getText().length());
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	OnClickListener mCopyListener = new OnClickListener() {
		public void onClick(View v) {
			copyToClipboard(pEditor.getText());
			finish();
		}
	};
	
	/**
	 * A call-back for when the user presses the back button.
	 */
	OnClickListener mBackListener = new OnClickListener() {
		public void onClick(View v) {
			finish();
		}
	};

	/**
	 * A call-back for when the user presses the clear button.
	 */
	OnClickListener mClearListener = new OnClickListener() {
		public void onClick(View v) {
			mEditor.setText("");
		}
	};

	OnKeyListener mEditListener = new OnKeyListener() {

		public boolean onKey(View v, int keyCode, KeyEvent event) {
			pEditor.setText(mEditor.getText());
			return false;
		}
	};

	TextWatcher mEditWatch = new TextWatcher() {

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// pEditor.setText(mEditor.getText());
			String s1 = mEditor.getText().toString();
			// Pattern p = Pattern.compile("(\\w)");
			// Matcher m = p.matcher(mEditor.getText().toString());
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < s1.length(); i++) {
				Character c = s1.charAt(i);
				String r;
				r = (String) leetmap.get(c);
				if (r != null) {
					sb.append(r);
				} else {
					sb.append(c);
				}
			}
			// while (m.find()) {
			// String s11 = m.group(1);
			// Character c = s11.charAt(0);
			// String r;
			// r = (String) leetmap.get(c);
			// if (r!=null) {
			// sb.append(r);
			// } else {
			// sb.append(c);
			// }
			// }
			sb.append("(powered by Geek Twitter Helper)");
			pEditor.setText(sb);
			pEditor_len.setText(getText(R.string.result_length).toString()+pEditor.getText().length());
			mEditor_len.setText(getText(R.string.input_length).toString()+mEditor.getText().length());
			
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub

		}

		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub

		}
	};
}
